import React, {PureComponent} from 'react';
import {Link} from 'react-router-dom';
import {COMMON_TABLE_EMPTY_TEXT, TABLE, DATETIME_FORMAT} from '../constants';
import {Card, Table, Button} from 'antd';
import routes from './routes';
import {getWarrantyPolicy, abandonWarrantyPolicy, enableWarrantyPolicy} from './api';
import {warrantyPolicyStatus} from '../Enum';
import {formatDateTime} from '../utils';
import {computeSelectedRows} from './utils';
import {formatMessage} from './intl';
import styles from './style.css';

export default class AbandonEnable extends PureComponent {
    state = {
        loading: false,
        data: [],
        isError: false,
        selectedRowKeys: [],
        selectedRows: [],
    };

    componentDidMount() {
        this.getData();
    }

    getData = () => {
        this.setState({loading: true});
        const status = [];
        if(this.props.page === 'enable')
            status.push(warrantyPolicyStatus.新建);
        if(this.props.page === 'abandon') {
            status.push(warrantyPolicyStatus.新建);
            status.push(warrantyPolicyStatus.生效);
        }
        getWarrantyPolicy({status}).then(res => {
            if(res.ok)
                this.setState({
                    data: res.data.content,
                    loading: false,
                    isError: false
                });
            else
                this.setState({
                    data: [],
                    loading: false,
                    isError: true
                });
        });
    };
    
    onSubmitAbandon = () => {
        this.setState({loading: true});
        const data = this.state.selectedRows.map(v => ({
            rowVersion: v.rowVersion,
            id: v.id,
        }));
        return abandonWarrantyPolicy(data).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.onCancel();
            return res.ok;
        });
    }
    onSubmitEnable = () => {
        this.setState({loading: true});
        const data = this.state.selectedRows.map(v => ({
            rowVersion: v.rowVersion,
            id: v.id,
        }));
        return enableWarrantyPolicy(data).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.onCancel();
            return res.ok;
        });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    render() {
        const columns = [
            {
                title: formatMessage({
                    id: 'abandonEnable.column.code',
                    defaultMessage: '编号'
                }),
                dataIndex: 'code',
                sorter: true,
                render: (text, record) => (
                    <Link key="detail" to={routes.detail.format(record.id)}>
                        {text}
                    </Link>
                )
            },
            {
                title: formatMessage({
                    id: 'abandonEnable.column.name',
                    defaultMessage: '名称'
                }),
                dataIndex: 'name'
            },
            {
                title: formatMessage({
                    id: 'queryPage.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
                render: (text, record) => `(${record.brandCode})${record.brandName}`
            },
            {
                title: formatMessage({
                    id: 'queryPage.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
                render: (text, record) => `(${record.dealerCode})${record.dealerName}`
            },
            {
                title: formatMessage({
                    id: 'queryPage.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country'
            },
            {
                title: formatMessage({
                    id: 'abandonEnable.column.startTime',
                    defaultMessage: '启用日期'
                }),
                sorter: true,
                dataIndex: 'startTime',
                render: text => formatDateTime(text, DATETIME_FORMAT)
            },
            {
                title: formatMessage({
                    id: 'abandonEnable.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark'
            }
        ];
        const alertMessage = (
            <div>
                <span>
                    {formatMessage({
                        id: 'abandonEnable.alertMessage.span',
                        defaultMessage: '查询失败，请'
                    })}
                    <a onClick={this.getData}>
                        {formatMessage({
                            id: 'abandonEnable.alertMessage.refresh',
                            defaultMessage: '刷新'
                        })}
                    </a>
                    {formatMessage({
                        id: 'abandonEnable.alertMessage.',
                        defaultMessage: '重试'
                    })}
                </span>
            </div>
        );
        const locale = {
            emptyText: this.state.isError ? alertMessage : COMMON_TABLE_EMPTY_TEXT
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            }
        };
        return (
            <div>
                <Card>
                    <Table
                        className="white-space-nowrap"
                        columns={columns}
                        dataSource={this.state.data}
                        rowKey="id"
                        pagination={false}
                        locale={locale}
                        loading={this.state.loading}
                        rowSelection={rowSelection}
                        {...TABLE} />
                </Card>
                <Card className={styles.optionBtn}>
                    <Button
                        type="primary"
                        onClick={this.props.page === 'abandon' ? this.onSubmitAbandon : this.onSubmitEnable}
                        disabled={!(this.state.selectedRowKeys.length > 0)}
                        loading={this.state.loading}>
                        {formatMessage({
                            id: 'approvePanel.operation.onSubmit',
                            defaultMessage: '保存'
                        })}
                    </Button>
                </Card>
                <div className="page-toolbar">
                    <Button type="primary" href={`#${routes.query.url()}`}>
                        {formatMessage({
                            id: 'abandonEnable.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
